package cn.huiyunche.driver.service.impl;

import cn.huiyunche.base.service.interfaces.DWaybillService;
import cn.huiyunche.base.service.interfaces.TmsOrderService;
import cn.huiyunche.base.service.mappers.WaybillGenerateResultsMapper;
import cn.huiyunche.base.service.mappers.ext.WaybillGenerateResultsExtMapper;
import cn.huiyunche.base.service.model.DWaybill;
import cn.huiyunche.base.service.model.TmsOrder;
import cn.huiyunche.base.service.model.WaybillGenerateResults;
import cn.huiyunche.base.service.model.WaybillGenerateResultsExample;
import cn.huiyunche.base.service.vo.OrderCostTo;
import cn.huiyunche.base.service.vo.PageVo;
import cn.huiyunche.base.service.vo.WaybillGenerateResultsVo;
import cn.huiyunche.driver.service.OrderService;
import cn.huiyunche.driver.service.WaybillGenerateResultsService;
import cn.huiyunche.driver.service.query.WaybillGenerateResultsQueryConditions;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @FileName: cn.huiyunche.driver.service.impl
 * @Description: Description
 * @author: Aaron
 * @date: 2017/3/9 下午2:47
 */
@Service
public class WaybillGenerateResultsServiceImpl implements WaybillGenerateResultsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(WaybillGenerateResultsService.class);

    @Autowired
    private WaybillGenerateResultsMapper waybillGenerateResultsMapper;

    @Autowired
    private WaybillGenerateResultsExtMapper waybillGenerateResultsExtMapper;

    @Autowired
    private DWaybillService dWaybillService;

    @Autowired
    private TmsOrderService tmsOrderService;

    @Autowired
    private OrderService orderService;

    @Override
    public Long addWaybillGenerateResults(WaybillGenerateResults result) {
        LOGGER.info("WaybillGenerateResultsServiceImpl.add param : {}", result);

        if (null == result) {
            LOGGER.error("WaybillGenerateResultsServiceImpl.add param result must not be null");
            throw new IllegalArgumentException("生成结果不能为空");
        }

        waybillGenerateResultsMapper.insertSelective(result);

        return result.getId();
    }

    @Override
    public Map<String, Object> selectListByConditions(PageVo pageVo, WaybillGenerateResultsQueryConditions conditions) {
        if (null == conditions) {
            LOGGER.error("ScPriceconfOcServiceImpl.selectListByConditions param conditions must not be null");
        }

        Map<String, Object> map = new HashMap<>();

        String orderByClause = null;
        if (null != pageVo) {
            orderByClause = StringUtils.isNotBlank(pageVo.getOrder()) == true ? pageVo.getOrder() : " gr.gmt_create DESC";
        }

        Map<String, Object> paramsMap = new HashedMap();

        if (StringUtils.isNotBlank(conditions.getOrderLineId())) {
            paramsMap.put("order_line_id", conditions.getOrderLineId() + "%");
        }

        if (StringUtils.isNotBlank(conditions.getOrderCode())) {
            paramsMap.put("order_code", "%" + conditions.getOrderCode() + "%");
        }

        if (null != conditions.getIsGenerated()) {
            paramsMap.put("is_generated", conditions.getIsGenerated());
        }

        if (StringUtils.isNotBlank(conditions.getErrMsg())) {
            paramsMap.put("err_msg", "%" + conditions.getErrMsg() + "%");
        }

        if (null != pageVo) {
            pageVo.setTotalRecord(waybillGenerateResultsExtMapper.countByConditions(paramsMap));
            paramsMap.put("limitStart", pageVo.getStartIndex());
            paramsMap.put("limitEnd", pageVo.getPageSize());
            paramsMap.put("orderByClause", orderByClause);
        }

        List<WaybillGenerateResultsVo> list = waybillGenerateResultsExtMapper.selectByConditions(paramsMap);

        //反序列
        if(!CollectionUtils.isEmpty(list)){
            for (WaybillGenerateResultsVo resultsVo:list) {
                //反序列化费用信息
                OrderCostTo orderCostTo = null;
                if(StringUtils.isNotBlank(resultsVo.getOrdercost())){
                    orderCostTo = JSONObject.parseObject(resultsVo.getOrdercost().replaceAll("\"", ""), OrderCostTo.class);
                    resultsVo.setOrderCostTo(orderCostTo);
                }
            }
        }

        map.put("list", list);

        if (null != pageVo) {
            map.put("page", pageVo);
        }

        return map;
    }

    @Override
    public void regenerate(String ids) {
        LOGGER.info("WaybillGenerateResultsServiceImpl.regenerate param : {}", ids);

        if ( StringUtils.isBlank(ids) || 0 == ids.split(",").length ) {
            LOGGER.error("WaybillGenerateResultsServiceImpl.regenerate param ids must not be null");
            throw new IllegalArgumentException("主键不能为空");
        }

        String[] split = ids.split(",");
        for (int i = 0; i < split.length; i++) {

            TmsOrder tmsOrder = tmsOrderService.selectByPrimaryKey(Long.parseLong(split[i]));

            if (tmsOrder == null) {
                LOGGER.error("WaybillGenerateResultsServiceImpl.regenerate tms order must not be null");
                throw new BusinessException("订单不能为空");
            }

            WaybillGenerateResults generateResults = this.selectByOrderId(Long.parseLong(split[i]));

            try {

                //生成运单

                DWaybill dWaybill = dWaybillService.selectByOrderLineId(tmsOrder.getIlineid());
                if ( null != dWaybill ) {
                    LOGGER.error("WaybillGenerateResultsServiceImpl.regenerate waybill already exist");
                    continue;
                }

                DWaybill waybill = dWaybillService.addByTmsOrder(tmsOrder);

                generateResults.setIsGenerated(true);

                //添加队列
                //20170328 liangpeng 去掉订单添加到redis操作，原因是会影响派单顺序，造成后排队司机先接单。
                //orderService.addQueue(tmsOrder, waybill);
            } catch (Exception e) {
                LOGGER.error("OrderServiceImpl.handleTmsOrders error : {}", e);

                generateResults.setErrMsg(e.getMessage());
            }

            //更新错误记录
            waybillGenerateResultsMapper.updateByPrimaryKeySelective(generateResults);
        }
    }

    @Override
    public WaybillGenerateResults selectByOrderId(Long orderId) {
        LOGGER.info("WaybillGenerateResultsServiceImpl.selectByOrderId param : {}", orderId);

        if ( null == orderId || 0 == orderId.longValue() ) {
            LOGGER.error("WaybillGenerateResultsServiceImpl.selectByOrderId param order id must not be null");
            throw new IllegalArgumentException("订单主键不能为空");
        }

        WaybillGenerateResultsExample example = new WaybillGenerateResultsExample();
        example.createCriteria().andOrderIdEqualTo(orderId);

        List<WaybillGenerateResults> list = waybillGenerateResultsMapper.selectByExample(example);

        if ( CollectionUtils.isNotEmpty(list) ) {
            return list.get(0);
        }

        return null;
    }
}
